package com.neoden.notes;

import com.neoden.notes.data.NotesProvider;
import com.neoden.notes.models.NotesModel;
import com.neoden.notes.util.DialogHelpers;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class NotesListActivity extends ListActivity
{
	private static final String TAG = NotesListActivity.class.getName();
	
	Cursor mCursor;
	NotesModel mModel;

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes_list);

        mModel = new NotesModel(this);
        
        // TODO: list selection, sort order
        renewCursor();
        
        registerForContextMenu(getListView());
    }

	@SuppressWarnings("deprecation")
	private void renewCursor() {
		if (mCursor != null && !mCursor.isClosed()) {
			stopManagingCursor(mCursor);
			mCursor.close();
		}
		mCursor = mModel.getAllNotes(mModel.getCurrentListId());
		startManagingCursor(mCursor);
		ListAdapter adapter = new NotesListCursorAdapter(this, mCursor);
        setListAdapter(adapter);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_notes_list, menu);
        return true;
    }

	@SuppressWarnings("deprecation")
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		stopManagingCursor(mCursor);
		mCursor.close();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Intent intent = new Intent(this, NoteEditorActivity.class);
		intent.putExtra(NoteEditorActivity.EXTRA_ID, id);
		startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		final Context context = this;

		switch (item.getItemId()) {
		case R.id.menu_new:
			
			Intent intent = new Intent(this, NoteEditorActivity.class);
			intent.setAction(Intent.ACTION_SEND);
			startActivity(intent);
			return true;
			
		case R.id.menu_new_list:
			
			DialogHelpers.submitText(this, getString(R.string.title_list_title), null, 
					new DialogHelpers.OnSubmitTextListener() {
						public void onSubmitText(String text) {
							mModel.setCurrentListId(mModel.createList(text));
							renewCursor();
						}
					});
			return true;
			
		case R.id.menu_select_list:
			
			DialogHelpers.selectFromList(this, getString(R.string.title_select_list), mModel.getAllLists(), 
					new DialogHelpers.OnSelectListener() {
						public void onSelect(long id) {
							mModel.setCurrentListId(id);
							renewCursor();
						}
					});
			return true;
			
		case R.id.menu_rename_list:
			
			DialogHelpers.selectFromList(context, getString(R.string.title_select_list), mModel.getAllLists(), 
					new DialogHelpers.OnSelectListener() {
						public void onSelect(long id) {
							final long innerId = id;
							DialogHelpers.submitText(context, getString(R.string.title_rename_list), 
									mModel.getListTitle(id), 
									new DialogHelpers.OnSubmitTextListener() {
										public void onSubmitText(String text) {
											mModel.renameList(innerId, text);
										}
									}
							);
						}
					});
			return true;

		case R.id.menu_delete_list:

			// TODO: disable delete list menu item when only one list remains
			
			final Cursor cursor = mModel.getAllLists();
			long rowCount = cursor.getCount();
			cursor.close();
			
			if (rowCount == 1) {
				// don't allow to delete last list
				return true;
			}

			DialogHelpers.confirm(context, null, getString(R.string.msg_delete_list_confirmation), 
					new DialogHelpers.OnConfirmListener() {
						public void onConfirm() {
							// move to the first list
							long idToDelete = mModel.getCurrentListId();
							Cursor c = mModel.getAllLists();
							c.moveToFirst();
							long firstId = c.getLong(
									c.getColumnIndex(NotesProvider.Lists.COLUMN_ID));
							mModel.setCurrentListId(firstId);
							renewCursor();
							mModel.deleteList(idToDelete);
							c.close();
						}
					}
			);
			return true;
			
		default:
			Log.w(TAG, "No handler for menu item: id = " + item.getItemId());
			return false;
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) 
	{
		getMenuInflater().inflate(R.menu.context_notes_list, menu);
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onContextItemSelected(MenuItem item) 
	{
        AdapterView.AdapterContextMenuInfo info;
        
        try {
            info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            Log.e(TAG, "Bad menuInfo", e);
            return false;
        }
        
        final long id = getListAdapter().getItemId(info.position);		
		
		switch (item.getItemId()) {
		
		case R.id.menu_delete:

			DialogHelpers.confirm(this, null, getString(R.string.msg_delete_confirmation), 
					new DialogHelpers.OnConfirmListener() {
						public void onConfirm() {
							mModel.deleteNote(id);
							mCursor.requery();
						}
					}
			);
			return true;

		case R.id.menu_share:
			Note note = mModel.getNote(id);
			
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			intent.putExtra(Intent.EXTRA_TEXT, note.getNote());
			intent.putExtra(Intent.EXTRA_SUBJECT, note.getTitle());
			intent.setType("text/plain");
			
			startActivity(intent);
			return true;
			
		default:
			Log.w(TAG, "No handler for menu item: id = " + item.getItemId());
			return false;
		}
	}
}
